#include "LogicSys.h"

LogicSys::~LogicSys()
{	
	_b_stop = true;
	_consume.notify_one();
	_work_thread.join();
}

void LogicSys::PostMsgToQue(std::shared_ptr<LogicNode> msg)
{
	std::unique_lock<std::mutex> lock(_mtx);
	std::cout << "PostMsgToQue" << std::endl;
	_msg_que.emplace(msg);
	if (_msg_que.size() == 1) {
		lock.unlock();
		_consume.notify_one();
	}
}

LogicSys& LogicSys::getInst()
{
	static LogicSys instance;
	return instance;
}

LogicSys::LogicSys():_b_stop(false) {
	RegisterCallBack();
	_work_thread = std::thread(&LogicSys::DealMsg,this);
}

void LogicSys::DealMsg()
{
	for (;;) {
		std::unique_lock<std::mutex> lock(_mtx);
		if (_msg_que.empty() && !_b_stop) {
			_consume.wait(lock);
		}
		if (_b_stop) {
			while (!_msg_que.empty()) {
				auto& msg = _msg_que.front();
				std::cout << "msg_id is " << msg->_recvnode->_msg_id << std::endl;
				auto iter = _fun_callbacks.find(msg->_recvnode->_msg_id);
				if (iter == _fun_callbacks.end()) {
					_msg_que.pop();
					continue;
				}
				iter->second(msg->_session, msg->_recvnode->_msg_id, std::string(msg->_recvnode->_data, msg->_recvnode->_total_size));
				_msg_que.pop();
			}
			break;
		}
		auto& msg = _msg_que.front();
		std::cout << "msg_id is " << msg->_recvnode->_msg_id << std::endl;
		auto iter = _fun_callbacks.find(msg->_recvnode->_msg_id);
		if (iter == _fun_callbacks.end()) {
			_msg_que.pop();
			continue;
		}
		iter->second(msg->_session, msg->_recvnode->_msg_id, std::string(msg->_recvnode->_data, msg->_recvnode->_total_size));
		_msg_que.pop();


	}
}

void LogicSys::RegisterCallBack()
{
	_fun_callbacks[1001] = std::bind(&LogicSys::HelloWorldCallBack, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
}

void LogicSys::HelloWorldCallBack(std::shared_ptr<CSession> session, const short& msg_id, const std::string& data)
{
	Json::Value value;
	Json::Reader reader;
	reader.parse(data, value);
	std::cout << "receive id is " << value["id"] << "data is " << value["data"] << std::endl;
	//value["data"] = "Server received data:" + value["data"].asString();
	std::string return_data = value.toStyledString();
	std::cout << "Send data is :" << return_data << std::endl;
	session->Send(return_data, msg_id);
	
}
